import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Statistic, Typography, Space, Button, Avatar, List, Tag, Progress, message } from 'antd';
import {
  ShoppingCartOutlined,
  UserOutlined,
  ShopOutlined,
  DollarOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  TrophyOutlined,
  TeamOutlined,
  RiseOutlined,
  FallOutlined,
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { useAppDispatch, useAppSelector } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import DashboardService, { DashboardStats, SalesTrendData, RegionData, OrderStatsData } from '../../services/dashboardService';

const { Title, Text } = Typography;

const Dashboard: React.FC = () => {
  const dispatch = useAppDispatch();
  const [loading, setLoading] = useState(false);
  const [dashboardStats, setDashboardStats] = useState<DashboardStats | null>(null);
  const [salesTrendData, setSalesTrendData] = useState<SalesTrendData | null>(null);
  const [regionData, setRegionData] = useState<RegionData[]>([]);
  const [orderStatsData, setOrderStatsData] = useState<OrderStatsData | null>(null);

  // 设置面包屑
  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页' },
      { title: '仪表板' },
    ]));
  }, [dispatch]);

  // 加载仪表板数据
  const loadDashboardData = async () => {
    try {
      setLoading(true);
      const [stats, salesTrend, regionStats, orderStats] = await Promise.all([
        DashboardService.getDashboardStats(),
        DashboardService.getSalesTrend(),
        DashboardService.getRegionStats(),
        DashboardService.getOrderStats()
      ]);

      setDashboardStats(stats);
      setSalesTrendData(salesTrend);
      setRegionData(regionStats);
      setOrderStatsData(orderStats);
    } catch (error) {
      message.error('加载仪表板数据失败');
      console.error('Dashboard data loading error:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadDashboardData();
  }, []);

  // 统计卡片数据
  const stats = dashboardStats && dashboardStats.trends ? [
    {
      title: '上月总订单',
      value: dashboardStats.totalOrders,
      icon: <ShoppingCartOutlined />,
      trend: dashboardStats.trends.orders,
      color: '#1890ff',
      bgColor: 'rgba(24, 144, 255, 0.1)',
    },
    {
      title: '上月总收入',
      value: dashboardStats.totalRevenue,
      suffix: 'K',
      icon: <DollarOutlined />,
      trend: dashboardStats.trends.revenue,
      color: '#52c41a',
      bgColor: 'rgba(82, 196, 26, 0.1)',
    },
    {
      title: '上月利润',
      value: dashboardStats.totalProfit,
      icon: <TrophyOutlined />,
      trend: dashboardStats.trends.profit,
      color: '#faad14',
      bgColor: 'rgba(250, 173, 20, 0.1)',
    },
    {
      title: '上月新增用户',
      value: dashboardStats.newUsers,
      icon: <TeamOutlined />,
      trend: dashboardStats.trends.users,
      color: '#722ed1',
      bgColor: 'rgba(114, 46, 209, 0.1)',
    },
  ] : [];

  // 销售趋势图表配置
  const salesTrendOption = salesTrendData ? {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['交易额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: salesTrendData.months
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '交易额',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#1890ff'
        },
        areaStyle: {
          opacity: 0.8,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(24, 144, 255, 0.8)'
            }, {
              offset: 1, color: 'rgba(24, 144, 255, 0.1)'
            }]
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: salesTrendData.sales
      }
    ]
  } : {};

  // 近10日订单统计
  const orderStatsOption = orderStatsData ? {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['订单总数', '异常订单']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: orderStatsData.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单总数',
        type: 'bar',
        data: orderStatsData.totalOrders,
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '异常订单',
        type: 'line',
        data: orderStatsData.abnormalOrders,
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  } : {};

  return (
    <div style={{ padding: '24px' }}>
      {/* 头部信息 */}
      <div style={{ marginBottom: '24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <Title level={3} style={{ margin: 0, marginBottom: '8px' }}>
            <Avatar src="https://avatars.githubusercontent.com/u/1?v=4" size="small" style={{ marginRight: '8px' }} />
            TROVE-ADMIN ⭐
            <Tag color="blue" style={{ marginLeft: '8px' }}>管理员</Tag>
            <Tag color="green">在线</Tag>
          </Title>
          <Text type="secondary">
            君可白衣如雪，清风明月，再听一曲月下。🌙
          </Text>
        </div>
        <Space>
          <Button type="primary">管理面板</Button>
        </Space>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        {stats.map((stat, index) => (
          <Col xs={24} sm={12} lg={6} key={index}>
            <Card
              hoverable
              className="dashboard-stat-card"
              style={{
                borderRadius: '12px',
                background: `linear-gradient(135deg, ${stat.bgColor} 0%, rgba(255,255,255,0.1) 100%)`,
                border: `1px solid ${stat.color}20`
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontSize: '14px',
                    color: '#666',
                    marginBottom: '8px',
                    fontWeight: 500
                  }}>
                    {stat.title}
                  </div>
                  <div style={{
                    fontSize: '28px',
                    fontWeight: 'bold',
                    color: stat.color,
                    marginBottom: '8px'
                  }}>
                    {stat.value.toLocaleString()}{stat.suffix || ''}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    {stat.trend > 0 ? (
                      <RiseOutlined style={{ color: '#52c41a', marginRight: '4px' }} />
                    ) : (
                      <FallOutlined style={{ color: '#ff4d4f', marginRight: '4px' }} />
                    )}
                    <span style={{
                      color: stat.trend > 0 ? '#52c41a' : '#ff4d4f',
                      fontSize: '12px',
                      fontWeight: 500
                    }}>
                      {Math.abs(stat.trend)}%
                    </span>
                  </div>
                </div>
                <div style={{
                  fontSize: '40px',
                  color: stat.color,
                  opacity: 0.8,
                  marginLeft: '16px'
                }}>
                  {stat.icon}
                </div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 销售趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24}>
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>📈 日交易趋势</span>
                <Space>
                  <Button size="small">今日</Button>
                  <Button size="small">本月</Button>
                  <Button size="small" type="primary">本年</Button>
                </Space>
              </div>
            }
            style={{ borderRadius: '12px' }}
          >
            <ReactECharts
              option={salesTrendOption}
              style={{ height: '300px' }}
              opts={{ renderer: 'canvas' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 数据统计和排行 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={12}>
          <Card
            title="🌍 地区异常订单排行"
            style={{ borderRadius: '12px' }}
          >
            <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
              {regionData.map((item, index) => (
                <div key={index} style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '8px 0',
                  borderBottom: index < regionData.length - 1 ? '1px solid #f0f0f0' : 'none'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{
                      width: '8px',
                      height: '8px',
                      borderRadius: '50%',
                      backgroundColor: item.color,
                      marginRight: '12px'
                    }} />
                    <span>{item.name}</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Progress
                      percent={regionData.length > 0 ? (item.value / Math.max(...regionData.map(r => r.value))) * 100 : 0}
                      showInfo={false}
                      strokeColor={item.color}
                      style={{ width: '60px', marginRight: '12px' }}
                    />
                    <span style={{ fontWeight: 'bold', color: item.color }}>
                      {item.value}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card
            title="📊 近10日订单"
            style={{ borderRadius: '12px' }}
          >
            <ReactECharts
              option={orderStatsOption}
              style={{ height: '300px' }}
              opts={{ renderer: 'canvas' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 动态信息 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card
            title="🔔 系统动态"
            style={{ borderRadius: '12px' }}
            extra={<Button type="link" size="small">更多</Button>}
          >
            <List
              size="small"
              dataSource={[
                {
                  title: 'KOI-ADMIN ⭐ 开启了新的人生！',
                  time: '2023-11-23 18:00:00',
                  type: 'success'
                },
                {
                  title: '企业级中台管理平台',
                  time: '2023-11-23 18:00:00',
                  type: 'info'
                },
                {
                  title: '四种布局方式，多种主题',
                  time: '2023-11-23 18:00:00',
                  type: 'warning'
                },
                {
                  title: 'ElementPlus + Vue3 + TypeScript + Pinia',
                  time: '2023-11-23 18:00:00',
                  type: 'info'
                },
                {
                  title: '欢迎大家star#fork，喜欢的可以点明星哦 😊',
                  time: '2023-11-23 18:00:00',
                  type: 'error'
                }
              ]}
              renderItem={(item) => (
                <List.Item>
                  <div style={{ width: '100%' }}>
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: '4px' }}>
                      <div style={{
                        width: '6px',
                        height: '6px',
                        borderRadius: '50%',
                        backgroundColor:
                          item.type === 'success' ? '#52c41a' :
                            item.type === 'warning' ? '#faad14' :
                              item.type === 'error' ? '#ff4d4f' : '#1890ff',
                        marginRight: '8px'
                      }} />
                      <Text style={{ fontSize: '13px' }}>{item.title}</Text>
                    </div>
                    <Text type="secondary" style={{ fontSize: '12px', marginLeft: '14px' }}>
                      {item.time}
                    </Text>
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card
            title="📈 每日日记"
            style={{ borderRadius: '12px' }}
            extra={<Button type="link" size="small">更多</Button>}
          >
            <List
              size="small"
              dataSource={[
                {
                  title: '你好像有点不对劲哦，我好像对你有点意思了，你好像对我也有点意思。',
                  time: '2023-11-23 18:00:00'
                },
                {
                  title: '今天又工作了，我一个月工资1500，价格会涨到你买不起吗？是不是觉得我很便宜？',
                  time: '2023-11-23 18:00:00'
                },
                {
                  title: '听说你想要一套房子，你好像对我也有点意思。',
                  time: '2023-11-23 18:00:00'
                }
              ]}
              renderItem={(item) => (
                <List.Item>
                  <div style={{ width: '100%' }}>
                    <Text style={{ fontSize: '13px', lineHeight: '1.5' }}>{item.title}</Text>
                    <div style={{ marginTop: '8px' }}>
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        {item.time}
                      </Text>
                    </div>
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;
